package com.sy.service.impl;

import com.sy.dto.Volume;
import com.sy.entity.Video;
import com.sy.service.VideoService;
import com.sy.utils.RedisOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.sy.constant.BusinessConstant.*;

@Service
public class VideoServiceImp extends BaseServiceImpl implements VideoService {
    @Autowired
    private RedisOperations redisOperations;

    @Override
    public List<Video> getAllVideos() {
        return videoMapper.getAllVideos();
    }

    @Override
    public void loadVideoVolumeDataToRedis() {
        //1.判断Redis中有无所有视频的排行数据
        //如果Redis中没有排行数据则将其从MySQL数据库加载到Redis中
        if (!redisOperations.exists(REDIS_VIDEO_VOLUME_KEY)) {
            System.out.println("正在加载数据库中点击量数据到Redis中...");
            //(1)获取当前数据库中所有的视频点击量数据
            List<Volume> volumeList = videoMapper.getAllVolumeData();
            Map<String, Double> volumeMap = new HashMap<>();
            //(2)将得到的点击量数据通过Redis中的sorted set保存
            //视频id作为成员，点击量作为分值
            volumeList.forEach(volumeData -> volumeMap.put(String.valueOf(volumeData.getId()), volumeData.getVolume()));
            //(3)将排行榜数据存入Redis中
            redisOperations.zadd(REDIS_VIDEO_VOLUME_KEY, volumeMap);
        }
    }

    @Override
    public List<Video> getHottestVideos() {
        List<Video> videos = new ArrayList<>();
        //1.先去判断Redis中有无排行数据
        //(1)如果没有，就将点击量数据加载到Redis中
        if (!redisOperations.exists(REDIS_VIDEO_VOLUME_KEY)) {
            loadVideoVolumeDataToRedis();
        } else {
            //(2)如果有，就查询出点击量排名在前10的视频id
            Set<String> topVolumeIds = redisOperations.zrevrange(REDIS_VIDEO_VOLUME_KEY, REDIS_VOLUME_DATA_MIN_INDEX, REDIS_VOLUME_DATA_MAX_INDEX);
            //通过这些视频Id到数据库中查询对应的所有的视频信息
            videos = videoMapper.getVideosVolumeByIds(new ArrayList<>(topVolumeIds));
        }
        return videos;
    }

    @Override
    public void incrPlayVolume(Integer id) {
        if (Objects.isNull(id)) {
            buildError(HttpStatus.NOT_FOUND, "视频id不能为空");
        }
        videoMapper.incrPlayVolume(id);
        //对Redis中的视频播放量进行+1操作
        redisOperations.zincrby(REDIS_VIDEO_VOLUME_KEY, String.valueOf(id), VOLUME_INCR);
    }

    @Override
    public Video getVideoById(Integer id) {
        if (Objects.isNull(id)) {
            buildError(HttpStatus.NOT_FOUND, "视频id不能为空");
        }
        return videoMapper.getVideoById(id);
    }
}
